#include "logindialog.h"
#include <QApplication>
#include "dataprovider.h"

LoginDialog::LoginDialog(QWidget *parent)
    : QDialog(parent)
{
    setWindowIcon(QIcon(":/icons/icon/logo.jpg"));
    setupUI();
    applyStyles();
    setupConnections();
}

void LoginDialog::setupUI() {
    setWindowTitle("好用得效期系统");
    setFixedSize(420, 620);
    QString tenant = "";
    QString userCode = "";
    ShopInfo* shop = DataProvider::instance()->GetShopInfo();
    if (shop != nullptr) {
        qDebug() << "门店信息：" << shop->ShopCode;
        tenant = shop->TenantSign;
        userCode = shop->ShopCode;
    }

    // 控件初始化
    titleLabel = new QLabel("欢迎登录", this);
    tenantLabel = new QLabel("机构编码:", this);
    usernameLabel = new QLabel("门店编码:", this);
    passwordLabel = new QLabel("密码:", this);
    tenantEdit = new QLineEdit(this);
    usernameEdit = new QLineEdit(this);
    passwordEdit = new QLineEdit(this);
    loginButton = new QPushButton("登录", this);
    exitButton = new QPushButton("退出", this);
    keyboard = new DigitalKeyboard(this);

    // 输入框配置
    tenantEdit->setPlaceholderText("请输入机构编码");
    if (!tenant.isEmpty()){
        tenantEdit->setText(tenant);
        usernameEdit->setFocus();
    }
    usernameEdit->setPlaceholderText("请输入门店编码");
    if (!userCode.isEmpty()) {
        usernameEdit->setText(userCode);
        passwordEdit->setFocus();
    }
    passwordEdit->setPlaceholderText("请输入密码");
    passwordEdit->setEchoMode(QLineEdit::Password);
    tenantEdit->installEventFilter(this);
    usernameEdit->installEventFilter(this);
    passwordEdit->installEventFilter(this);

    // 布局管理
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    QHBoxLayout *tenantLayout = new QHBoxLayout();
    QHBoxLayout *usernameLayout = new QHBoxLayout();
    QHBoxLayout *passwordLayout = new QHBoxLayout();
    QHBoxLayout *buttonLayout = new QHBoxLayout();

    mainLayout->addWidget(titleLabel);
    mainLayout->addSpacing(15);

    tenantLayout->addWidget(tenantLabel, 1);
    tenantLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    tenantLayout->addWidget(tenantEdit, 4);
    mainLayout->addLayout(tenantLayout);
    mainLayout->addSpacing(8);

    usernameLayout->addWidget(usernameLabel, 1);
    usernameLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    usernameLayout->addWidget(usernameEdit, 4);
    mainLayout->addLayout(usernameLayout);
    mainLayout->addSpacing(8);

    passwordLayout->addWidget(passwordLabel, 1);
    passwordLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    passwordLayout->addWidget(passwordEdit, 4);
    mainLayout->addLayout(passwordLayout);
    mainLayout->addSpacing(15);

    buttonLayout->addWidget(loginButton);
    buttonLayout->addSpacing(5);
    buttonLayout->addWidget(exitButton);
    buttonLayout->setContentsMargins(10, 0, 5, 0);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addSpacing(15);
    mainLayout->addWidget(keyboard);
    mainLayout->setAlignment(keyboard, Qt::AlignCenter);
    keyboard->show();
}

void LoginDialog::applyStyles() {
    setStyleSheet(R"(
        QDialog { background: #f0f2f5; }
        QLabel { font: 14px; color: #333; }
        QLineEdit {
            padding:8px;
            border:1px solid #ddd;
            border-radius:4px;
            font: 14px;
        }
        QPushButton {
          padding:10px 20px;
          border:2px solid #ddd;
          border-radius:4px;
          font:bold 14px;
        }
        QPushButton[text="登录"] { background:#4890ee; color:white; height: 40px; font: 24px bold;}
        QPushButton[text="登录"]:hover { background:#40a9ff; }
        QPushButton[text="退出"] { background:#ff6666; color:white; height: 40px; font: 24px bold;}
        )"
        );

    titleLabel->setStyleSheet("font: bold 28px; color: #1a73e8;");
    titleLabel->setAlignment(Qt::AlignCenter);
}

void LoginDialog::setupConnections() {
    DataProvider* provider = DataProvider::instance();
    connect(loginButton, &QPushButton::clicked, this, &LoginDialog::attemptLogin);
    connect(exitButton, &QPushButton::clicked, this, &LoginDialog::exitApplication);

    connect(provider, &DataProvider::proccessFailed, this, [=](const QString &error){
        QMessageBox::warning(this, "登录失败", error, QMessageBox::Ok);
        passwordEdit->clear();
        passwordEdit->setFocus();
        loginButton->setEnabled(true);
    });

    connect(provider, &DataProvider::proccessReady, this, [=](){
        // disconnect(provider, &DataProvider::proccessReady, this, nullptr);
        QObject::disconnect(provider, nullptr, this, nullptr);
        accept();
    });
}

void LoginDialog::attemptLogin() {
    QString tenant = tenantEdit->text().trimmed();
    QString username = usernameEdit->text().trimmed();
    QString password = passwordEdit->text();

    if (tenant.isEmpty()) {
        QMessageBox::warning(this, "登录失败", "请输入机构编码", QMessageBox::Ok);
        tenantEdit->setFocus();
        return;
    }

    if (username.isEmpty()) {
        QMessageBox::warning(this, "登录失败", "请输入门店编码", QMessageBox::Ok);
        usernameEdit->setFocus();
        return;
    }

    if (password.isEmpty()) {
        QMessageBox::warning(this, "登录失败", "请输入密码", QMessageBox::Ok);
        passwordEdit->setFocus();
        return;
    }

    loginButton->setDisabled(true);

    DataProvider* provider = DataProvider::instance();
    provider->Login(tenant, username, password);
    return;
}

void LoginDialog::exitApplication() {
    disconnect();
    close();
}

bool LoginDialog::eventFilter(QObject *watched, QEvent *event) {
    if (event->type() == QEvent::FocusIn) {
        if (QLineEdit *lineEdit = qobject_cast<QLineEdit*>(watched)) {
            keyboard->attachTo(lineEdit);
        }
    }
    return QWidget::eventFilter(watched, event);
}
